package com.zed.games.repository;

import com.zed.api.common.ApplicationContextSupport;
import com.zed.api.games.Action;
import com.zed.api.games.GameAlreadyExistException;
import com.zed.api.games.GameBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * 基于SPI的游戏构建器加载
 *
 * @author Zed
 */
abstract class GameBuilderLoaderWithSpi extends ApplicationContextSupport {

    private final Logger LOGGER = LoggerFactory.getLogger(GameBuilderLoaderWithSpi.class);

    /**
     * 基于系统开启时加载
     *
     * @param context {@link ApplicationContext}
     */
    @Override
    protected void bindApplicationContext(ApplicationContext context) {
        ServiceLoader<GameBuilder> loader = ServiceLoader.load(GameBuilder.class);
        Iterator<GameBuilder> iterator = loader.iterator();
        while (iterator.hasNext()) {
            GameBuilder<?, ? extends Action> builder = (GameBuilder<?, ? extends Action>) iterator.next();
            try {
                this.addGameBuilder(builder);
            } catch (GameAlreadyExistException e) {
                LOGGER.error("duplication the game builder -> {}", builder.getId());
            }
        }
        super.bindApplicationContext(context);
    }

    /**
     * 添加游戏构建器
     *
     * @param builder {@link GameBuilder}
     */
    protected abstract void addGameBuilder(GameBuilder<?, ? extends Action> builder) throws GameAlreadyExistException;

}
